package com.mugui.spring.net.baghandle;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.springframework.context.ApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import com.mugui.Mugui;
import com.mugui.spring.base.ModelInterface;
import com.mugui.spring.base.Module;
import com.mugui.spring.net.bean.Message;
import com.mugui.spring.net.bean.NetBag;

public class NetBagModule implements ModelInterface {
	private NetBagModuleManager manager = null;

	@Override
	public void stop() {

	}

	@Override
	public void start() {

	}

	@Override
	public boolean isrun() {
		return false;
	}

	private ApplicationContext applicationContext = null;

	@Override
	public void init() {
		if (applicationContext == null)
			applicationContext = (ApplicationContext) System.getProperties().get("Application");
		if (applicationContext != null) {
			manager = applicationContext.getBean(NetBagModuleManager.class);
		}
		if (manager == null) {
			throw new RuntimeException("启动错误：" + NetBagModuleManager.class + " 未初始化");
		}
	}

	public void init(Module module, Mugui obj) {
		init();
		this.module = module;
		object = applicationContext.getBean(obj.getClass());

		initMethods();
	}

	private void initMethods() {
		Method[] methods2 = object.getClass().getMethods();
		for (Method method : methods2) {
			method.setAccessible(true);
			methods.put(method.getName(), method);
		}
	}

	private HashMap<String, Method> methods = new HashMap<>();

	Mugui object = null;
	Module module = null;

	public Message runFunc(NetBag bag) throws Exception {
		String func[] = bag.getFunc().split("[.]");
		Method method = methods.get(func[func.length - 1]);
		if (method == null) {
			throw new RuntimeException(object.getClass().getName() + " not find " + func[func.length - 1]);
		}
		return (Message) method.invoke(object, bag);
	}

}
